<template>
  <!--  -->
  <div class="heritage-industry">
    <!-- 地图容器 -->
    <div id="container" class="container">
      <div class="map-buttons">
        <el-button
          type="text"
          size="mini"
          @click="addRoadLayer"
          v-show="!roadNetwork"
          class="map-btn map-element"
          >{{ lang === "zh_cn" ? "打开路网" : "Open road" }}</el-button
        >
        <el-button
          type="text"
          size="mini"
          @click="removeRoadLayer"
          v-show="roadNetwork"
          class="map-btn map-element"
          >{{ lang === "zh_cn" ? "关闭路网" : "Close road" }}</el-button
        >

        <el-button
          type="text"
          size="mini"
          @click="addSatellite"
          v-show="isOrdMap"
          class="map-btn map-element"
          >{{ lang === "zh_cn" ? "卫星地图" : "Satellite map" }}</el-button
        >
        <el-button
          type="text"
          size="mini"
          @click="removeSatellite"
          v-show="!isOrdMap"
          class="map-btn map-element"
          >{{ lang === "zh_cn" ? "普通地图" : "General map" }}</el-button
        >

        <el-button
          type="text"
          size="mini"
          @click="resetMap"
          class="map-btn map-element"
          >{{ lang === "zh_cn" ? "复位" : "Reset" }}</el-button
        >
      </div>
      <div class="EchartsBox" id="EchartsBox"></div>
      <!-- 几何查询弹框 -->
    </div>
  </div>
</template>

<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=2eccb47b400c8ab58f2dc596dbfe9d53&plugin=AMap.MouseTool,AMap.DistrictSearch"></script>
<script>
import * as echarts from "echarts/core";
import {
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from "echarts/components";
import { LineChart } from "echarts/charts";
import { UniversalTransition } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";

echarts.use([
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
]);

import { mapState, mapMutations } from "vuex";
export default {
  name: "HeritageIndustry",

  data() {
    return {
      map: "",
      district: null,
      polygons: [],
      zoom: 9,
      marker: null, //点位

      // 弹框内容
      title: "",
      content: [],
      infoWindow: null,

      dataList: null, // 数据
      isOrdMap: true, //判断是卫星图还是普通图，普通图为true
      satellite: null, //用来存储卫星地图影像
      roadNetwork: false, //是否具有路网，默认没有
      roadNetLayer: null, //用来存储路网

      // 带有输入建议的搜索框
      restaurants: [],
      searchIndustry: "",
      searchObj: null,
      markers: [],

      // 几何查询
      geometrySearchType: "circle",
      geometryBox: false, //几何查询面板隐藏展示
      mouseTool: null,
      overlays: [], //绘制好的覆盖物
      geometrySearchRes: [], //几何查询结果
      issearchRes: true, //查询结果图标显示隐藏

      // 类型查询
      options: [
        {
          type: "test",
          name: "test",
        },
      ],
      typeSelect: "test",

      list: [],

      data1: [
        [12, 12, 11, 14, 9, 23, 21],
        [22, 18, 19, 23, 29, 33, 31],
        [15, 22, 21, 14, 19, 33, 41],
        [32, 32, 31, 34, 39, 33, 32],
      ],

      data2: [
        [21, 16, 33, 14, 29, 23, 12],
        [18, 32, 44, 35, 14, 33, 26],
        [17, 11, 32, 15, 29, 13, 24],
        [32, 21, 54, 18, 28, 34, 23],
      ],
      data3: [
        [12, 45, 32, 27, 18, 23, 41],
        [23, 31, 25, 13, 19, 23, 29],
        [15, 13, 28, 19, 19, 25, 37],
        [34, 28, 41, 32, 56, 11, 24],
      ],
    };
  },

  computed: {
    ...mapState(["lang", "dataArr"]),
  },
  async created() {
    this.dataList = this.dataArr;

    this.getAllType(); //初始化下拉菜单
    this.changeinstryType("one");
  },

  mounted() {
    this.initMap(); //初始化地图
    this.drawMian();
    // this.disSearch();
    this.addMarker();
    this.mouseTool = new AMap.MouseTool(this.map);

    // console.log("test", this.map.getZoom());
    // this.mapZoom();

    // console.log("返回所有覆盖物", this.map.getAllOverlays("marker"));
  },

  methods: {
    ...mapMutations(["changeinstryType"]),

    initMap() {
      //初始化地图
      this.map = new AMap.Map("container", {
        resizeEnable: true,
        zoom: this.zoom, //级别
        zooms: [1, 18],
        center: [114.341552, 30.546222], //中心点坐标
        viewMode: "3D", //使用3D视图
        lang: this.lang,
        mapStyle: "amap://styles/normal",
        infoWindow: null,
      });
    },

    // 裁剪边界

    drawHotMap() {
      this.$message({
        message: "热力图绘制中，初次加载可能用时较长",
      });

      for (let i = 0; i < this.dataList.length; i++) {
        this.list.push({
          coordinate: this.dataList[i].coordinate,
          count: this.dataList[i].num,
        });
      }

      this.layer = new Loca.HeatmapLayer({
        map: this.map,
        fitView: true,
      });
      console.log("this.list", this.list);
      this.layer.setData(this.list, {
        lnglat: "coordinate",
        value: "count",
      });

      //  radius为热力半径，由于初期数据未录入，故设置的较大，默认为16，后续数据全部录入后再进行修改。
      this.layer.setOptions({
        style: {
          radius: 100,
          color: {
            0.5: "#2c7bb6",
            0.65: "#abd9e9",
            0.7: "#ffffbf",
            0.9: "#fde468",
            1.0: "#d7191c",
          },
        },
      });

      this.layer.render();
    },

    drawMian() {
      var path1 = [
        new AMap.LngLat(113.729686, 30.881821),
        new AMap.LngLat(113.997135, 30.936904),
        new AMap.LngLat(113.911991, 30.801348),
      ];

      var path2 = [
        new AMap.LngLat(114.713816, 31.227725),
        new AMap.LngLat(115.323558, 31.130206),
        new AMap.LngLat(115.327677, 31.452925),
        new AMap.LngLat(115.039286, 31.493919),
      ];
      var path3 = [
        new AMap.LngLat(114.950089, 30.205599),
        new AMap.LngLat(115.024934, 29.978059),
        new AMap.LngLat(115.723939, 30.16702),
        new AMap.LngLat(115.283113, 30.553317),
        new AMap.LngLat(114.777741, 30.391163),
      ];

      var polygon = new AMap.Polygon({
        path: path1,
        strokeColor: "#F33", //线颜色
        strokeOpacity: 1, //线透明度
        strokeWeight: 3, //线粗细度
        fillColor: "#ee2200", //填充颜色
        fillOpacity: 0.35, //填充透明度
      });

      polygon.on("click", this.showInfoC);
      var polygon2 = new AMap.Polygon({
        path: path2,
        strokeColor: "#F33", //线颜色
        strokeOpacity: 1, //线透明度
        strokeWeight: 3, //线粗细度
        fillColor: "#ee2200", //填充颜色
        fillOpacity: 0.35, //填充透明度
      });
      var polygon3 = new AMap.Polygon({
        path: path3,
        strokeColor: "#F33", //线颜色
        strokeOpacity: 1, //线透明度
        strokeWeight: 3, //线粗细度
        fillColor: "#ee2200", //填充颜色
        fillOpacity: 0.35, //填充透明度
      });
      polygon2.on("click", this.showInfoC2);

      polygon3.on("click", this.showInfoC3);

      this.map.add([polygon, polygon2, polygon3]);
    },

    showInfoC() {
      console.log();
      var chartDom = document.getElementById("EchartsBox");
      var myChart = echarts.init(chartDom);
      var option;

      option = {
        // title: {
        //   text: "Stacked Line",
        // },
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: ["湿度%RH", "温度℃", "降水量mm", "风速m/10s"],
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: "风速m/10s",
            type: "line",
            stack: "Total",
            data: this.data1[0],
          },
          {
            name: "降水量mm",
            type: "line",
            stack: "Total",
            data: this.data1[1],
          },
          {
            name: "温度℃",
            type: "line",
            stack: "Total",
            data: this.data1[2],
          },
          {
            name: "湿度%RH",
            type: "line",
            stack: "Total",
            data: this.data1[3],
          },
        ],
      };

      option && myChart.setOption(option);
    },
    showInfoC2() {
      console.log();
      var chartDom = document.getElementById("EchartsBox");
      var myChart = echarts.init(chartDom);
      var option;

      option = {
        // title: {
        //   text: "Stacked Line",
        // },
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: ["湿度%RH", "温度℃", "降水量mm", "风速m/10s"],
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: "风速m/10s",
            type: "line",
            stack: "Total",
            data: this.data2[0],
          },
          {
            name: "降水量mm",
            type: "line",
            stack: "Total",
            data: this.data2[1],
          },
          {
            name: "温度℃",
            type: "line",
            stack: "Total",
            data: this.data2[2],
          },
          {
            name: "湿度%RH",
            type: "line",
            stack: "Total",
            data: this.data2[3],
          },
        ],
      };

      option && myChart.setOption(option);
    },
    showInfoC3() {
      console.log();
      var chartDom = document.getElementById("EchartsBox");
      var myChart = echarts.init(chartDom);
      var option;

      option = {
        // title: {
        //   text: "Stacked Line",
        // },
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: ["湿度%RH", "温度℃", "降水量mm", "风速m/10s"],
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: "风速m/10s",
            type: "line",
            stack: "Total",
            data: this.data3[0],
          },
          {
            name: "降水量mm",
            type: "line",
            stack: "Total",
            data: this.data3[1],
          },
          {
            name: "温度℃",
            type: "line",
            stack: "Total",
            data: this.data3[2],
          },
          {
            name: "湿度%RH",
            type: "line",
            stack: "Total",
            data: this.data3[3],
          },
        ],
      };

      option && myChart.setOption(option);
    },

    // 添加点集
    addMarker() {
      this.dataList = this.dataArr.map((ele) => {
        return {
          ...ele,
          coordinate: ele.coon.split(","),
        };
      });

      this.restaurant = this.dataList;
      console.log("请求结果", this.dataList);

      for (let i = 0; i < this.dataList.length; i++) {
        // 循环点坐标
        // 注意这里一定得用 let
        let marker = new AMap.Marker({
          // 自定义图标
          icon: new AMap.Icon({
            image:
              "https://mp-b0bd9cd4-ad06-4cf0-b1a3-ea2e46e926bc.cdn.bspapp.com/cloudstorage/7bea69ff-bb2b-4667-8d33-eab9f0b9ed2b.png",
            size: new AMap.Size(45, 45),
            imageSize: new AMap.Size(45, 45),
          }),
          map: this.map,
          position: this.dataList[i].coordinate,
          extData: this.dataList[i],
        });

        this.markers.push(marker);

        AMap.event.addListener(marker, "click", () => {
          // this.nowMarker = marker;

          // console.log(this.infoWindow);
          this.title = this.dataList[i].ID;

          (this.content = [
            "火灾点ID：" + this.dataList[i].ID,

            "森林ID：" + this.dataList[i].slid,
            "坐标：" + this.dataList[i].coon,
            "影响度：" + this.dataList[i].num,
          ]),
            (this.infoWindow = new AMap.InfoWindow({
              isCustom: true, //使用自定义窗体
              // content: '  <div style="background-color:white">111</div>',
              content: this.createInfoWindow(
                this.title,
                this.content.join("<br/>")
              ),
              offset: new AMap.Pixel(16, -45),
            }));
          this.infoWindow.open(this.map, marker.getPosition());
          // console.log(marker.getPosition());
        });
      }

      // this.drawHotMap();
    },

    //渲染弹框
    createInfoWindow(title, content) {
      // console.log("11111111");
      var info = document.createElement("div");
      info.className = "custom-info input-card content-window-card";

      //可以通过下面的方式修改自定义窗体的宽高
      //info.style.width = "400px";
      // 定义顶部标题
      var top = document.createElement("div");
      var titleD = document.createElement("div");
      var closeX = document.createElement("img");
      top.className = "info-top";
      titleD.innerHTML = title;
      closeX.src = "https://webapi.amap.com/images/close2.gif";
      closeX.onclick = this.closeInfoWindow;

      top.appendChild(titleD);
      top.appendChild(closeX);
      info.appendChild(top);

      // 定义中部内容
      var middle = document.createElement("div");
      middle.className = "info-middle";
      middle.style.backgroundColor = "white";
      middle.innerHTML = content;
      info.appendChild(middle);

      // 定义底部内容
      var bottom = document.createElement("div");
      bottom.className = "info-bottom";
      bottom.style.position = "relative";
      bottom.style.top = "0px";
      bottom.style.margin = "0 auto";
      var sharp = document.createElement("img");
      sharp.src = "https://webapi.amap.com/images/sharp.png";
      bottom.appendChild(sharp);
      info.appendChild(bottom);
      return info;
    },

    // 关闭弹框
    closeInfoWindow() {
      this.map.clearInfoWindow();
      this.searchIndustry = null;
    },

    // 打开卫星地图
    addSatellite() {
      // console.log(111);
      this.isOrdMap = !this.isOrdMap;
      this.satellite = new AMap.TileLayer.Satellite();
      this.map.add(this.satellite);
    },

    // 关闭卫星地图
    removeSatellite() {
      this.isOrdMap = !this.isOrdMap;
      this.map.remove(this.satellite);
    },

    // 打开路网
    addRoadLayer() {
      this.roadNetwork = !this.roadNetwork;
      this.roadNetLayer = new AMap.TileLayer.RoadNet();
      this.map.add(this.roadNetLayer);
    },

    // 关闭路网
    removeRoadLayer() {
      this.roadNetwork = !this.roadNetwork;
      this.map.remove(this.roadNetLayer);
    },
    // 输入建议start
    handleSelect(item) {
      console.log(item);
      this.searchObj = item;
      console.log(this.searchIndustry);
    },

    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurants) => {
        return (
          restaurants.name.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },

    // 复位事件
    resetMap() {
      location.reload();
      // this.map.setCenter([115.464523, 38.874476]);
    },

    // 几何查询函数系列start
    opengeometryBox() {
      this.geometryBox = !this.geometryBox;
    },
    closegeometryBox() {
      this.geometryBox = !this.geometryBox;
    },
    // 集合查询函数系列start

    drawGeometry() {
      // if (this.geometrySearchType === "Rectangle") {

      if (!this.geometrySearchType) {
        this.$message({
          message: "请先选择几何元素类型再开始绘制",
          type: "warning",
        });
      }

      console.log(this.geometrySearchType);
      switch (this.geometrySearchType) {
        case "polygon": {
          this.mouseTool.polygon({
            fillColor: "#00b0ff",
            strokeColor: "#80d8ff",
            //同Polygon的Option设置
          });
          break;
        }
        case "rectangle": {
          this.mouseTool.rectangle({
            fillColor: "#00b0ff",
            strokeColor: "#80d8ff",
            //同Polygon的Option设置
          });
          break;
        }
        case "circle": {
          this.mouseTool.circle({
            fillColor: "#00b0ff",
            strokeColor: "#80d8ff",
            //同Circle的Option设置
          });
          break;
        }
      }
      // this.mouseTool.close(); //关闭，并清除覆盖物
      this.mouseTool.on("draw", (e) => {
        this.overlays.push(e.obj);
        // console.log("e.obj---------", e.obj.contains([115.638353, 39.004825]));

        // 遍历点位，判断是否在范围内
        for (let i = 0; i < this.dataList.length; i++) {
          if (e.obj.contains(this.dataList[i].coordinate)) {
            if (
              !this.geometrySearchRes.some(
                (ele) => ele.name === this.dataList[i].name
              )
            ) {
              this.geometrySearchRes.push(this.dataList[i]);
            }
          }
        }
        // console.log("几何查询结果geometrySearchRes", this.geometrySearchRes);
        this.mouseTool.close(); //关闭
        this.geometrySearchType = null;
      }); //解除绑定，
    },

    clearDrawGeometry() {
      this.mouseTool.close(true);
      this.geometrySearchRes = [];
    },
    closeDraw() {
      this.mouseTool.close(true);
      this.geometryBox = false;

      this.geometrySearchRes = [];
    },

    changeissearchRes() {
      this.issearchRes = !this.issearchRes;
    },

    // 查询结果跳转详情
    lookthis(row) {
      console.log(row);
      // this.$router.push({
      //   name: `industryMain`,
      //   params: { heritage: row._id },
      // });
      this.$router.push("/heritage/industry/main/" + row.row._id);
    },

    // 类型查询start
    async getAllType() {
      // var res = await this.$axios.get(
      //   "/getHeritageMainData/getHeritageMainData"
      // );
      // res = res.data.data;
      // console.log("请求结果", res);
      // this.dataList = res.data.data;
      // console.log(this.dataList);

      for (let i = 0; i < this.dataList.length; i++) {
        if (!this.options.some((ele) => ele.type === this.dataList[i].name)) {
          this.options.push(this.dataList[i]);
        }
      }
      console.log(this.options);
    },

    searchTypeClick() {
      console.log(this.typeSelect);
      this.map.remove(this.markers);
      this.map.clearInfoWindow();
      if (this.typeSelect === "test") {
        this.addMarker();
      } else {
        var filEnd = this.dataList.filter(
          (ele) => ele.name === this.typeSelect
        );
        console.log(filEnd);
        // this.map.clearMap();
        for (let i = 0; i < filEnd.length; i++) {
          // 循环点坐标
          // 注意这里一定得用 let
          let marker = new AMap.Marker({
            map: this.map,
            position: filEnd[i].coordinate,
            extData: filEnd[i],
          });

          this.map.setCenter(filEnd[i].coordinate); //设置地图中心点为当前位置

          this.markers.push(marker);

          AMap.event.addListener(marker, "click", () => {
            // this.nowMarker = marker;

            // console.log(this.infoWindow);
            this.title = filEnd[i].name;

            (this.content = [
              "开放日期：" + filEnd[i].start,

              "开放时间：" + filEnd[i].prolevel,
              "票价：" + filEnd[i].company,
              "故居简介：" + filEnd[i].brief,
            ]),
              (this.infoWindow = new AMap.InfoWindow({
                isCustom: true, //使用自定义窗体
                // content: '  <div style="background-color:white">111</div>',
                content: this.createInfoWindow(
                  this.title,
                  this.content.join("<br/>")
                ),
                offset: new AMap.Pixel(16, -45),
              }));
            this.infoWindow.open(this.map, marker.getPosition());

            // console.log(marker.getPosition());
          });
        }
        // this.map.setFitView();
        // AMap.event.addDomListener(
        //   document.getElementById("selectBtn"),
        //   "click",
        //   () => {
        //     this.map.setFitView();
        //   }
        // );
      }
    },
    // 类型查询end
  },
};
</script>

<style>
.EchartsBox {
  position: fixed !important;
  top: 120px;
  right: 15px;
  width: 400px;
  height: 300px;
  background: white;
  border: 1px solid #ccc;
  border-radius: 10px;
  z-index: 999;
}

.heritage-industry #container {
  border-bottom: 1px solid #f9d5a7;
}
/* 弹框样式 */
.content-window-card {
  position: relative;
  box-shadow: none;
  bottom: 0;
  left: 0;
  width: auto;
  padding: 0;
}

.content-window-card p {
  height: 2rem;
}

.custom-info {
  border: solid 1px silver;
  width: 280px;
  background-color: white;
}

div.info-top {
  position: relative;
  background: none repeat scroll 0 0 #f9f9f9;
  border-bottom: 1px solid #ccc;
  border-radius: 5px 5px 0 0;
}

div.info-top div {
  display: inline-block;
  color: #333333;
  font-size: 14px;
  font-weight: bold;
  line-height: 31px;
  padding: 0 10px;
}

div.info-top img {
  position: absolute;
  top: 10px;
  right: 10px;
  transition-duration: 0.25s;
}

div.info-middle {
  font-size: 12px;
  padding: 10px 6px;
  line-height: 20px;
}
div.info-middle img {
  width: 100px;
  height: 70px;
  padding-bottom: 10px;
}

div.info-bottom {
  height: 0px;
  width: 100%;
  clear: both;
  text-align: center;
}

div.info-bottom img {
  position: relative;
  z-index: 104;
}

span {
  margin-left: 5px;
  font-size: 11px;
}

.info-middle img {
  float: left;
  margin-right: 6px;
}

.xiangxi {
  color: #555;
}

/* 地图元件样式 */

.heritage-industry .map-buttons {
  padding: 15px;
  z-index: 999;
  position: absolute;
  top: 0;
  right: 0;
}

.heritage-industry .geometrySearch {
  position: absolute;
  top: 60px;
  right: 0;
  z-index: 999;
  background-color: white;
  padding: 15px;
  border-radius: 5px;
  margin-right: 15px;
  border: 1px solid #dcdfe6;
}

.heritage-industry .geometrySearch .geometryType {
  display: block;
  padding-bottom: 15px;
  color: #606266;
}
.heritage-industry .geometrySearch .geometryBtns {
  padding-top: 15px;
}

.heritage-industry .map-buttons .closegeometryBox {
  margin-left: 0;
}

.heritage-industry .geometrySearch .searchRes {
  padding-top: 15px;
}

.heritage-industry .geometrySearch .searchRes .el-form-item__label {
  font-size: 12px;
  color: #111;
}
.heritage-industry .geometrySearch .searchRes .el-form-item {
  margin: 0;
  padding-left: 10px;
}
.heritage-industry .map-buttons .el-input__inner {
  border-top-right-radius: 0px;
  border-bottom-right-radius: 0px;
  border-right: none;
}
.heritage-industry .map-buttons .selectBtn {
  border-top-left-radius: 0px;
  border-bottom-left-radius: 0px;
  margin-right: 10px;
}
</style>